<?php

namespace app\api\controller\order;

use app\api\controller\BaseController;
use app\models\user\User;
use app\models\user\WechatUser;
use app\Request;
use services\pay\WxPay;
use services\SystemConfigService;
use services\UtilService;
use app\models\store\StoreOrderCar;
use think\cache\driver\Redis;
use think\facade\Db;
use utils\Json;

/**
 * 订单管理控制器
 * Class StoreOrderController
 * @package app\api\controller\order
 */
class StoreOrderCarController extends BaseController
{
    /**
     * 获取全部的订单
     * @param Request $request
     * @return Json
     */
    public function lst(Request $request)
    {
        list($type, $page, $limit) = UtilService::getMore([
            ['status', ''],
            ['page', 0],
            ['limit', ''],
        ], $request, true);
        return app('json')->successful(StoreOrderCar::getUserOrderSearchList($request->uid(), $type, $page, $limit));
    }


    /**
     * 洗车
     * @param Request $request
     */
    public function washCar(Request $request)
    {
        $device_id = $request->param("device_id");
        $device_data = Db::name("store_device")->where("id", $device_id)->value("car_order_id");
        if ($device_data != 0) {
            return app("json")->fail("设备正在工作中~");
        }
        $uid = $request->uid(); // 会员的ID
        $type = $request->param("type");    // 洗车的类型 10 微信支付 20 积分支付 30 洗车券扣除
        if ($request->method() == "GET") {
            $card_id = $request->param("car_id");
            $store_id = $request->param('store_id');
            $userInfo = User::get(["uid" => $uid]);
            if (!$userInfo) return app("fail")->fail("用户的信息不存在");
            // 获取门店的信息
            $storeInfo = Db::name("system_store")->where("id", $store_id)->field("id, wash_price, wash_point")->find();
            if (!$storeInfo) return app("json")->fail("门店信息不存在");
            switch ($type) {
                case 10:    // 微信支付
                    // 获取一些参数
                    $wxConfig = SystemConfigService::more(['routine_appId', 'routine_appsecret', 'pay_weixin_mchid', 'pay_weixin_key']);

                    $wxpay = new WxPay([
                        "app_id" => $wxConfig['routine_appId'],
                        'app_secret' => $wxConfig['routine_appsecret'],
                        'mchid' => $wxConfig['pay_weixin_mchid'],
                        'apikey' => $wxConfig['pay_weixin_key']
                    ]);
                    $title = "洗车消费";
                    $orderNum = $this->createOrderNo();
                    $orderData = [
                        'order_id' => $orderNum,
                        'uid' => $uid,
                        'real_name' => $userInfo["real_name"] ?: $userInfo["nickname"],
                        'total_price' => $storeInfo["wash_price"],
                        'pay_time' => 0,
                        'pay_type' => 10,
                        'add_time' => time(),
                        'remark' => date("Y-m-d H:i:s", time()) . "会员洗车",
                        'status' => 1,
                        'wxapp_id' => $this->wxapp_id,
                        'car_id' => $card_id,
                        'store_id' => $store_id,
                        'device_id' => $device_id
                    ];
                    $order_id = Db::name("store_order_car")->insertGetId($orderData);
                    // 添加洗车的记录
                    $billData = [
                        'uid' => $uid,
                        'link_id' => $order_id,
                        'pm' => 0,
                        'title' => $title,
                        'category' => "now_money",
                        'type' => 1,
                        'number' => $storeInfo["wash_price"],
                        'balance' => $storeInfo["wash_price"],
                        'mark' => date("Y-m-d H:i:s", time()) . "会员洗车消费",
                        'add_time' => time(),
                        'wxapp_id' => $this->wxapp_id,
                        "order_num" => $orderNum,
                        'is_pay' => 0,
                    ];
                    Db::name("user_bill")->insertGetId($billData);
                    $result = $wxpay->unifiedorder(
                        $orderNum,
                        WechatUser::getOpenId($request->uid()),
                        $storeInfo["wash_price"],
                        $title
                    );
                    $result["order_id"] = $order_id;
                    return app("json")->successful(compact('result'));
                    break;
                case 20:    // 积分支付
                    // 获取所需要的积分
                    $needPoint = $storeInfo["wash_point"];
                    // 获取用户的积分
                    $userPoint = $userInfo["integral"];
                    if ($userPoint < $needPoint) {
                        return app("json")->fail("您的积分不足，请充值");
                    }
                    // 添加订单的记录
                    $orderData = [
                        'order_id' => $this->createOrderNo(),
                        'uid' => $uid,
                        'real_name' => $userInfo["real_name"] ?: $userInfo["nickname"],
                        'total_price' => $needPoint,
                        'pay_time' => time(),
                        'pay_type' => 20,
                        'add_time' => time(),
                        'remark' => date("Y-m-d H:i:s", time()) . "会员洗车",
                        'status' => 1,
                        'wxapp_id' => $this->wxapp_id,
                        'car_id' => $card_id,
                        'store_id' => $store_id,
                        'is_pay' => 1,
                        'device_id' => $device_id
                    ];
                    $order_id = Db::name("store_order_car")->insertGetId($orderData);
                    // 添加积分的操作记录
                    $pointData = [
                        'uid' => $uid,
                        'change' => 10,
                        "num" => $needPoint,
                        'add_time' => time(),
                        'wxapp_id' => $this->wxapp_id,
                        'type' => 30,
                        'order_id' => $order_id
                    ];
                    Db::name("user_point_log")->save($pointData);
                    $f = Db::name("user")->where("uid", $uid)->dec("integral", $needPoint)->update();
                    if ($f) return app("json")->successful("支付成功", compact("order_id"));
                    else return app("json")->fail("支付失败");
                    break;
                case 30:    // 洗车券支付
                    $coupon_id = $request->param("coupon_id");
                    if (!$coupon_id) return app("json")->fail("优惠券不存在");
                    $couponData = Db::name("store_coupon_user")->where("id", $coupon_id)->find();
                    if (!$couponData) return app("json")->fail("优惠券不存在");
                    if ($couponData["status"] == 1) return app("json")->fail("优惠券已过期");
                    if ($couponData["status"] == 2) return app("json")->fail("优惠券过期");
                    if ($couponData["end_time"] < time()) return app("json")->fail("优惠券过期");
                    // 消费优惠券
                    $orderData = [
                        'order_id' => $this->createOrderNo(),
                        'uid' => $uid,
                        'real_name' => $userInfo["real_name"] ?: $userInfo["nickname"],
                        'total_price' => $storeInfo["wash_price"],
                        'pay_time' => time(),
                        'pay_type' => 30,
                        'add_time' => time(),
                        'remark' => date("Y-m-d H:i:s", time()) . "会员洗车",
                        'status' => 1,
                        'wxapp_id' => $this->wxapp_id,
                        'car_id' => $card_id,
                        'store_id' => $store_id,
                        'is_pay' => 1,
                        'device_id' => $device_id
                    ];
                    $order_id = Db::name("store_order_car")->insertGetId($orderData);
                    $f = Db::name("store_coupon_user")->where("id", $coupon_id)->update([
                        'status' => 1,
                        'use_time' => time(),
                    ]);
                    if ($f) return app("json")->successful("支付成功", compact("order_id"));
                    else return app("json")->fail("支付失败");
                    break;
                default:
                    return app("json")->fail("支付方式错误");
            }
        } elseif ($request->method() == "POST") {
            // 支付的回调
            switch ($type) {
                case 10:    // 微信支付
                    $order_id = $request->param("order_id");
                    // 获取数据
                    $bill_id = Db::name("user_bill")->where("wxapp_id", $this->wxapp_id)->where("type", 1)->where("link_id", $order_id)->value("id");
                    Db::name("store_order_car")->where("id", $order_id)->update([
                        'is_pay' => 1,
                        'pay_time' => time(),
                    ]);
                    // 更新余额的操作记录
                    Db::name("user_bill")->where("id", $bill_id)->update([
                        'pay_time' => time(),
                        'is_pay' => 1,
                    ]);
                    return app("json")->successful("支付成功");
                    break;
                case 20:    // 积分
                    break;
                case 30:    // 优惠券
                    break;
                default:
                    return app("json")->fail("请求参数错误");
            }
        } else {
            return app("json")->fail("请求方式错误");
        }

    }


    /**
     *
     * @param Request $request
     * @return Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function orderDetail(Request $request)
    {
        $order_id = $request->param("order_id") ?? 0;
        if (!$order_id) return app("json")->fail("无订单");
        // 获取订单的数据
        $data = Db::name("store_order_car")->alias("s")
            ->join("system_store ss", "ss.id = s.store_id", "LEFT")
            ->join("user_car c", "c.id = s.car_id", "LEFT")
            ->where("s.id", $order_id)
            ->field("s.id, s.order_id, s.add_time, pay_type, total_price, car_coupon_id, ss.name, c.license_no")
            ->find();
        if (!$data) return app("json")->fail("获取订单数据失败，请稍后再试~");
        $data["add_time"] = date("Y-m-d H:i:s", $data["add_time"]);
        return app("json")->successful(compact("data"));
    }


    /**
     * 门店的详情
     * @param Request $request
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function storeInfo(Request $request)
    {
        $store_id = $request->param("store_id") ?? 0;
        if (!$store_id) return app("json")->fail("请传入门店的ID");
        // 获取门店的数据
        $data = Db::name("system_store")->where("id", $store_id)
            ->field("id, name, address, phone, wash_price, wash_point")
            ->find();
        if (!$data) return app("json")->fail("门店不存在");
        return app("json")->successful(compact("data"));
    }

    /**
     * 前端定时访问|获取设备的信息
     * @param Request $request
     * @param integer $device_id 设备的ID
     */
    public function machineMsg(Request $request, $device_id = 0)
    {
        if (!$device_id) return app("json")->fail("请传入设备ID");
        $deviceData = Db::name("store_device")->where("id", $device_id)->where("is_del", 0)->find();
        if (!$deviceData) return app("json")->fail("设备信息不存在");
        // 返回设备信息
        return app("json")->successful(compact("deviceData"));
    }

    /**
     * 发送信息给设备
     * @param Request $request
     */
    public function send(Request $request)
    {
        $param = $request->param();
        $device_id = $param["device_id"];
        if (!$device_id) {
            return app("json")->fail("请选择设备");
        }
        // 绑定订单Id
        $deviceData = Db::name("store_device")->where("id", $device_id)->where("is_del", 0)->find();
        if (!$deviceData) {
            return app("json")->fail("获取数据失败");
        }
        if ($deviceData["car_order_id"] != 0 && $param["order_id"] != $deviceData['car_order_id']) {
            return app("json")->fail("设备在工作中");
        }
        Db::name("store_device")->where("id", $device_id)->update(["car_order_id" => $param["order_id"]]);
        $mask = strToHex($deviceData["bao_tou"] ?: "MyBr");
        $ver_mini = strToHex($deviceData["ver_mini"] ?: 0);
        $ver_high = strToHex($deviceData["ver_high"] ?: 0);
        $station_id = strToHex($deviceData["station_id"]);
        $module_id = strToHex($deviceData["module_id"]);
        $pwd = strToHex($deviceData["pwd"]);
        $tServer = strToHex(time());
        $cmd = strToHex("1");   // 开始洗车
        // 生成洗车的相关的秘钥
        $sendMsg = $mask.$ver_mini.$ver_high.$station_id.strToHex($device_id).$module_id.$pwd.$tServer.$cmd;
        $redis = new Redis();
        $wash_machine_data = $redis->get("wash_machine_data");
        if (!$wash_machine_data) {
            $wash_machine_data[] = $sendMsg;
            $redis->set("wash_machine_data", $wash_machine_data);
        }else{
            if (in_array($sendMsg, $wash_machine_data)) {
                return app("json")->fail("车辆已经正在清洗中~");
            }else{
                $wash_machine_data[] = $sendMsg;
                $redis->set("wash_machine_data", $wash_machine_data);
            }
        }
        return app("json")->successful("正在准备洗车");
    }


    /**
     * 判断
     * @param Request $request
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function judge(Request $request)
    {
        $device_id = $request->get("device_id");
        $deviceData = Db::name("store_device")->where("id", $device_id)->where("is_del", 0)->find();
        if (!$deviceData) {
            return app("json")->fail("获取数据失败");
        }
        if ($deviceData["car_order_id"] != 0) {
            return app("json")->fail("设备在工作中");
        }
        return app("json")->successful("可以洗车");
    }

}